// -----------------------------------------------------------------------
//  <copyright file="TopAdminRoleServiceBase.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2025 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025-02-17 09:02</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Authorization.Application.Queries;
using DaprPlus.Identity;


namespace DaprPlus.Authorization.Application;

using DaprPlus.Settings;

using Microsoft.Extensions.DependencyInjection;


/// <summary>
/// 最高权限管理角色服务基类
/// </summary>
/// <typeparam name="TRole">角色类型</typeparam>
/// <param name="provider"></param>
public class TopAdminRoleService<TRole>(IServiceProvider provider) : ITopAdminRoleService
    where TRole : class, IRole
{
    /// <summary>
    /// 是否最后权限管理角色
    /// </summary>
    /// <param name="roleNames">角色名集合</param>
    /// <returns></returns>
    public async Task<bool> IsTopAdminRole(params string[] roleNames)
    {
        var settingStore = provider.GetRequiredService<ISettingStore>();
        var setting = await settingStore.BuildSettingAsync<TopAdminRoleSetting>();
        var topRoleNames = setting.TopAdminRoleNames.Value?.Split(',', StringSplitOptions.RemoveEmptyEntries) ?? [];
        return roleNames.Intersect(topRoleNames).Any();
    }

    /// <summary>
    /// 是否最高权限管理角色
    /// </summary>
    public virtual async Task<bool> IsTopAdminRole(params long[] roleIds)
    {
        if (roleIds.Length == 0)
        {
            return false;
        }
        var roleNames = await GetRoleNames(roleIds);
        return await IsTopAdminRole(roleNames);
    }

    /// <summary>
    /// 获取角色名称
    /// </summary>
    protected virtual async Task<string[]> GetRoleNames(long[] roleIds)
    {
        var resolver = provider.GetRequiredService<IRoleNameResolver>();
        return await resolver.ResolveRoleName(roleIds);
    }
}
